<template>
  <div class="page">
    <div class="login">
      <el-container class="container">
        <el-header style="color: #333333">
          <h1>Register</h1>
        </el-header>
        <el-main style="width: 400px;">
          <div class="content">
            <el-form :model="user" status-icon :rules="rules" ref="user" label-width="100px" class="demo-user">
              <el-form-item label="账号" prop="userName">
                <el-input v-model="user.userName"></el-input>
              </el-form-item>
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="user.nickName"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="user.password" autocomplete="off" show-password clearable></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="user.checkPass" autocomplete="off" show-password clearable></el-input>
              </el-form-item>

            </el-form>

          </div>
          <el-tooltip placement="left">
            <div slot="content">头像上传</div>
            <el-upload
                class="avatar-uploader"
                action="api/User/addProfile"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="user.userImg!==''" :src="user.userImg | url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

          </el-tooltip>

        </el-main>

        <div class="login-button">
          <el-button round type="primary" @click="register">注册</el-button>
        </div>
        <div style=" margin: 0 auto;padding-bottom: 20px;padding-top: 20px;">
          <router-link to="/Login">

            <el-link type="primary">已有账号？去登录</el-link>
          </router-link>

        </div>
      </el-container>

    </div>

  </div>
</template>


<script>
import axios from 'axios';
import {isExistByUserName, registerUser} from "@/utils/api";

export default {
  name: "RegisterPage",
  props: {},

  data() {
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'));
      }
      if(value.length >10 || value.length <=1){
        return callback(new Error('账号长度应在 2-9 个字符'));
      }

      isExistByUserName({
        userName : value
      }).then(res => {
        if (res.code === 200) {
          // 如果账号存在
          if(res.objects){
            return callback(new Error('账号已注册'));
          }else{
            callback()
          }
        } else {
          return callback(new Error('系统错误,请联系管理员'));
        }
      })
    };
    var checkNickName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入昵称'));
      }
      if(value.length >10 || value.length <=1){
        return callback(new Error('昵称长度应在 2-9 个字符'));
      }
      callback()
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.user.checkPass !== '') {
          this.$refs.user.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.user.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      user: {
        password: '',
        checkPass: '',
        userName: '',
        userImg: "",
        nickName: "",
      },
      rules: {
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        userName: [
          { validator: checkUserName, trigger: 'blur' }
        ],
        nickName: [
          { validator: checkNickName , trigger: 'blur' }
        ]
      }
    }
  }, methods: {
    register() {
      this.$refs['user'].validate((valid) => {
        if (valid) {
          registerUser(this.user) .then(res => {
            if (res.code === 200) {

              this.$message({
                message: '注册成功,已跳转登录页面',
                type: 'success'
              });

              this.$router.push("/Login")
            } else {
              // console.log(res)
              this.$message({
                message: '注册失败,请联系管理员',
                type: 'error'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },

    handleAvatarSuccess(res, file) {
      // console.log(res)
      this.user.userImg = res.objects
      // this.$message.success("头像已上传")
      // this.notify("上传成功!","success","success");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    notify(msg,title,type) {
      this.$notify({
        title: title,
        message: msg,
        type: type
      });
    },
    }, watch: {},computed: {
    getUsername(){
      return this.getUser.userName;
    },
    getUser:{
      get(){
        return this.$store.getters.getUser;
      },
      set(value){
        return this.$store.commit("setUser",value);
      }
    }
  }, filters: {
    url(value){
      return "api/"+value;
    }
  }
}
</script>

<style scoped>
.page {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background: url("../assets/bg.webp") center center no-repeat;
  background-size: 100% 100%;

  /*min-height: 1080px;*/
  text-align: center;
  /*min-height: 1080px;*/
}

.container {
  width: 400px;
  margin: 0 auto;
  background: rgba(255, 255, 255, .1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .5);

}
>>>.el-form-item__label{
  color: #2c2c2c;
}
.login {
  color: #e9e9e9;

  width: 100%;
}

.content {
  width: 300px;
}

.Header {
  margin: 0 auto;
}

.login-button {
  margin: 0 auto;
}

>>> .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
>>>.avatar-uploader .el-upload:hover {
  border-color: #323436;
}
>>>.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 238px;
  height: 238px;
  line-height: 238px;
  text-align: center;
}
>>>.avatar {
  width: 238px;
  height: 238px;
  display: block;
}

</style>